<template>
  <div class="login-container min-h-full flex flex-col overflow-hidden">
    <!-- <header class="flex-none h-14 bg-white">
      <div class="flex items-center px-5 h-full">
        <img :src="logoUrl" class="h-8 object-cover cursor-pointer" />
      </div>
    </header> -->
    <div class="flex-1 flex items-start justify-center lg:justify-end">
      <div
        class="w-[460px] rounded-lg bg-white shadow-lg p-8 mt-36 lg:mr-[320px]"
      >
        <h1 class="font-bold text-2xl text-center">{{ websiteName }}</h1>
        <p class="text-gray-500 mt-2 pb-8 text-center">
          欢迎使用{{ websiteName }}
        </p>
        <el-form
          :model="loginForm"
          :rules="rules"
          ref="loginForm"
          class="demo-loginForm"
        >
          <el-form-item prop="username">
            <el-input placeholder="账号" v-model="loginForm.username" clearable>
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              placeholder="密码"
              v-model="loginForm.password"
              show-password
              clearable
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="validateCode">
            <div class="flex items-center gap-2">
              <el-input
                placeholder="请输入验证码"
                @change="submitForm('loginForm')"
                v-model="loginForm.validateCode"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
              <!-- 验证码图片 -->
              <img
                @click="refreshCode"
                :src="codeUrl"
                :class="{ invisible: !codeUrl }"
                class="w-20 flex-none h-7 object-cover cursor-pointer !select-none"
                alt="验证码图片"
              />
              <svg-icon
                @click="refreshCode"
                icon-class="refash"
                class="!w-9 !h-9 cursor-pointer !fill-gray-400"
              ></svg-icon>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="!space-x-0 space-y-2">
              <el-button
                :loading="loading"
                type="primary"
                size="medium"
                @click="submitForm('loginForm')"
                class="w-full flex justify-center"
              >
                <div class="align-middle flex items-center gap-2 text-md">
                  <svg-icon icon-class="login"></svg-icon>
                  <span>登录系统</span>
                </div>
              </el-button>
              <el-button
                size="medium"
                @click="idLogin"
                class="w-full flex justify-center"
              >
                <div class="align-middle flex items-center gap-2 text-md">
                  <span>使用交大ID登录</span>
                </div>
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchRefreshCode } from '@/api/user'
import { mapGetters } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      // 表单数据
      loginForm: {
        username: 'admin',
        password: '123456a~',
        validateCode: '',
        uuid: '',
        salt: ''
      },
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        validateCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      codeUrl: '', // 验证码图片数据
      // 重定向
      redirect: undefined,
      codeTimer: null
    }
  },
  computed: {
    ...mapGetters(['webInfo']),
    logoUrl() {
      return (
        (this.webInfo && this.webInfo.websiteLogo) ||
        require('@/assets/login_images/yidong.png')
      )
    },
    websiteName() {
      return (this.webInfo && this.webInfo.websiteName) || '西南交通大学舆情管理平台'
    }
  },
  watch: {
    // 监听路由变化
    $route: {
      handler: function (route) {
        if (route.query?.redirect) {
          try {
            // 解析原始重定向路径
            const [path, search] = route.query.redirect.split('?')
            const params = new URLSearchParams(search || '')

            // 合并其他查询参数
            Object.entries(route.query).forEach(([key, value]) => {
              if (key !== 'redirect' && value !== undefined) {
                params.set(key, value)
              }
            })

            // 重新构建完整路径
            this.redirect = params.toString()
              ? `${path}?${params.toString()}`
              : path
          } catch (e) {
            console.error('重定向参数解析失败:', e)
            this.redirect = route.query.redirect
          }
        } else {
          this.redirect = route.query?.redirect
        }
      },
      immediate: true
    }
  },
  /**
   * 在组件创建时执行初始化操作
   */
  created() {
    // 调用refreshCode方法刷新验证码
    this.refreshCode()

    // 每2分钟刷新一次验证码
    this.codeTimer = setInterval(() => {
      this.refreshCode()
    }, 1000 * 60 * 2)
  },
  destroyed() {
    // 在组件销毁时清除定时器
    clearInterval(this.codeTimer)
  },
  methods: {
    /**
     * 提交表单的方法
     * @param {String} formName - 表单的Ref名称，用于验证和提交特定的表单
     */
    submitForm(formName) {
      this.$router.push({ path: this.redirect || redirect || '/' })
      // 使用Element UI的表单验证功能，判断表单是否有效
      // this.$refs[formName].validate((valid) => {
      //   // 如果表单验证通过
      //   if (valid) {
      //     // 设置加载状态为true
      //     this.loading = true
      //     // 调用Vuex的dispatch方法，触发user模块中的login action进行登录
      //     this.$store
      //       .dispatch('user/login', this.loginForm)
      //       .then(() => {
      //         // 登录成功后，根据redirect的值进行页面跳转，默认跳转到首页
      //         const redirect = new URLSearchParams(location.search).get(
      //           'redirect'
      //         )
      //         this.$router.push({ path: this.redirect || redirect || '/' })
      //         // 设置加载状态为false
      //         this.loading = false
      //       })
      //       .catch(() => {
      //         // 如果登录失败，
      //         // 调用refreshCode方法刷新验证码
      //         this.refreshCode()
      //         // 清空验证码
      //         this.loginForm.validateCode = ''
      //         // 设置加载状态为false
      //         this.loading = false
      //       })
      //   }
      // })
    },
    /**
     * 异步刷新验证码
     *
     * 本函数通过调用fetchRefreshCode函数获取新的验证码信息，并更新页面上的验证码图片和相关数据
     * 如果返回的数据格式不正确，将抛出错误
     * 在更新数据时，使用临时对象来存储新的状态，以确保一次性更新所有相关数据
     * 如果更新失败，将在控制台输出错误信息
     */
    async refreshCode() {
      try {
        const response = await fetchRefreshCode()

        // 验证返回数据
        if (!response || !response.img || !response.salt || !response.uuid) {
          throw new Error('Invalid response format')
        }

        // 使用临时对象存储更新后的状态
        const updatedState = {
          codeUrl: response.img,
          uuid: response.uuid,
          salt: response.salt
        }

        // 一次性更新状态
        this.codeUrl = updatedState.codeUrl
        this.loginForm.uuid = updatedState.uuid
        this.loginForm.salt = updatedState.salt
      } catch (error) {
        console.error('Failed to refresh code:', error)
        this.$message.error('验证码刷新失败，请稍后再试')
      }
    },
    idLogin() {
      window.location.href = `http://192.168.124.54:8100/cas/login?service=${encodeURIComponent(
        'http://127.0.0.1:8023/yethan/login/cas'
      )}`
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  background-image: url(~@/assets/login_images/bg.png);
  background-position: left center;
  background-size: cover;
  background-repeat: no-repeat;
}
</style>
